package
{
	import flash.display.Sprite;
	import flash.display.StageQuality;
	import flash.events.Event;
	import flash.geom.PerspectiveProjection;
	import flash.geom.Point;

	import com.dogcatfishdish.anaglyph.TextBoxZ;
	
	[SWF(backgroundColor="#000000", width="450", height="450", frameRate="30")]
	public class Main extends Sprite
	{
		private var a:Vector.<TextBoxZ> = new Vector.<TextBoxZ>();
		private var container:Sprite;
		
		public function Main()
		{
			super();
	
			var per:PerspectiveProjection = new PerspectiveProjection();
			per.fieldOfView = 179;
			per.focalLength = 25
			per.projectionCenter = new Point(0, 0);
			
			container = new Sprite();
			container.x = stage.stageWidth * 0.5;
			container.y = stage.stageHeight * 0.5;
			container.transform.perspectiveProjection = per;
			
			for(var i:int = 0; i < 25; ++i) {
				var t:TextBoxZ = new TextBoxZ(Math.random() * 300);
				t.x = Math.random() * stage.stageWidth - container.x;
				t.y = Math.random() * stage.stageHeight - container.y;
				a.push(t);
				container.addChild(t);
			}
			addChild(container);
			
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function onEnterFrame(event:Event):void {
			sortZ();
			var item:TextBoxZ;
			for(var i:uint = 0, l:uint = a.length; i < l; ++i) {
				item = a[i];
				item.update();
				container.setChildIndex(item, i);
			}
		}
		
		private function sortZ():void
		{
			a.sort(function(a:TextBoxZ, b:TextBoxZ):Number {
				var n:Number = 0;
				if(a.z > b.z) {
					n = -1;
				} else if (a.z < b.z) {
					n = 1;
				}
				return n;
			});
		}
	}
}